<?php
/**
 * Created by PhpStorm.
 * User: yangzhic
 * Date: 2017/3/15
 * Time: 16:37
 */

namespace SDXApi\Controller;

use Com\Jdpay\JdpaySubmit;
use SDXApi\Service\QueueService;
use Think\Controller;

class CheckCacheController extends Controller {

    public function check_goods_practical_num_cache(){

        $goods_id = I('get.id');
        if($goods_id){
            $map = array('goods_id'=>$goods_id);
        }

        $goods_store_list = D('Goodsstorage')->where($map)->select();

        $error_goods = array();
        foreach($goods_store_list as $key=>$goods){
            $cache_goods_practical_num = S('goods_practical_num_cache_'.$goods['goods_id'].'_'.$goods['wid']);
            $cache_queue_goods_stock = S('queue_goods_stock_'.$goods['goods_id'].'_'.$goods['wid']);
            if(($cache_goods_practical_num!==false && $goods['practical_num']!=$cache_goods_practical_num) || ($cache_queue_goods_stock!==false && $cache_queue_goods_stock!=$cache_goods_practical_num)){
                $goods['cache_goods_practical_num'] = $cache_goods_practical_num;
                $goods['cache_queue_goods_stock'] = $cache_queue_goods_stock;
                $error_goods[] = $goods;
            }
        }

        $goods_total = count($goods_store_list);
        $error_goods_total = count($error_goods);

        $this->assign('goods_list',$error_goods);
        $this->assign('goods_total',$goods_total);
        $this->assign('error_goods_total',$error_goods_total);
        $this->display();
    }

    public function synchronization_goods_practical_num_cache(){
        $goods_store_list = D('Goodsstorage')->select();

        foreach($goods_store_list as $key=>$goods){
            $cache_goods_practical_num = S('goods_practical_num_cache_'.$goods['goods_id'].'_'.$goods['wid']);
            $cache_queue_goods_stock = S('queue_goods_stock_'.$goods['goods_id'].'_'.$goods['wid']);
            if($cache_goods_practical_num!==false && $goods['practical_num']!=$cache_goods_practical_num){
                $cache_goods_practical_num = $goods['practical_num'];
                set_goods_practical_num_cache($goods['goods_id'],$goods['wid'],$goods['practical_num']);
            }
            if($cache_queue_goods_stock!=$cache_goods_practical_num){
                set_queue_goods_stock($goods['goods_id'],$goods['wid'],$cache_goods_practical_num);
            }
        }

        $this->success('库存缓存同步完成');
    }

    public function test(){
        $uid = I('uid');
        $page_num = I("page");

        if(empty($uid)){
            returnApiError('uid不能为空');
        }

        $page_num = intval($page_num);
        $wid = I('wid');
        if(empty($page_num) || $page_num==0){
            $page_num = 1;
        }

        $purchased_number = C('PURCHASED_NUMBER');
        $order_goods = M('order_goods');

        $count_sql = "SELECT COUNT(*) as count FROM (
                          SELECT COUNT(og.goods_id) as num,o.`user_id`,og.* FROM sdx_order_goods og 
                          left join sdx_order_info o on og.order_id = o.order_id 
                          left join sdx_goods g on g.goods_id=og.goods_id 
                          WHERE o.user_id = ".$uid." AND o.shipping_status = ".SS_RECEIVED." AND o.order_status in(".OS_CONFIRMED.",".OS_SPLITED.")  AND g.is_on_sale = 1 AND g.is_delete = 0 AND g.is_alone_sale = 1 
                          GROUP BY og.goods_id having COUNT(og.goods_id)  >= ".$purchased_number.") t";

        $arcount = $order_goods->query($count_sql);

        $count = current($arcount);

        if($count['count']>0){
            $pagearr = show_page($count['count'], $page_num, C("page_size"));
            if($page_num>=$pagearr['pagecount']){
                $is_last=1;
            }else{
                $is_last=0;
            }

            $map = array(
                'o.user_id'=>$uid,
                'o.shipping_status'=>SS_RECEIVED,
                'o.order_status'=>array('in',array(OS_CONFIRMED,OS_SPLITED)),
                'g.is_on_sale'=>1,
                'g.is_delete'=>0,
                'g.is_alone_sale'=>1
            );

            $field = "og.goods_id,og.goods_name,COUNT(og.goods_id) as goods_buy_total,g.*";
            $goods_list = $order_goods->alias('og')
                ->field($field)
                ->join('left join '.C('DB_PREFIX').'order_info o on og.order_id = o.order_id')
                ->join('left join '.C('DB_PREFIX').'goods g on g.goods_id=og.goods_id')
                ->where($map)
                ->group('og.goods_id')
                ->having('COUNT(og.goods_id)>='.$purchased_number)
                ->limit($pagearr['firstpage'],$pagearr['pagesize'])
                ->select();
            $sql2 = $order_goods->getLastSql();

            $goods_list =  $this->get_goods_data($goods_list,$uid,$wid);
            $result = array('list'=>$goods_list,'is_last'=>$is_last,'sql1'=>$count_sql,'sql2'=>$sql2);
//            $result = array('list'=>$goods_list,'is_last'=>$is_last);
            returnApiSuccess($result);
        }else{
            returnApiError('常购清单中没有商品');
        }
    }

    public function queue_test(){
        $queue_key = 'order_queue';

        $uid = I('uid');
        $code = 'order_queue_user_'.$uid;

        $queue_service = new QueueService();

        $queue_service->add_queue($queue_key,$code);
        $check_res = $queue_service->check_order_queue($queue_key,$code);

        if($check_res['error']==0){
            echo 'ok';
        }else{
            echo $check_res['msg'];
        }


    }


    private function get_goods_data($goods_list,$uid,$wid){
        foreach($goods_list as $key=>$val){
            $is_booking = D('goods')->is_book_goods($val['goods_id'], $uid);
            if($is_booking){
                $goods_list[$key]['is_booking']='1';
            }else{
                $goods_list[$key]['is_booking']='0';
            }
        }
        $goods_list = D('goods')->convert_goods_info($goods_list,$wid, $uid);

        // 取得优惠活动
        $favourable_list = D('NewCart')->favourable_list_flow($uid,$wid);
        foreach($goods_list as $key=>$val){
            $goods_list[$key]['favourable_list'] = D('goods')->get_goods_favourable_list($favourable_list,$val);
        }

        return $goods_list;
    }

    public function test_app_pay(){
        $param = array();
        $amount = "1";
        $param["version"] = C('JD_VERSION');
        $param["merchant"] = C('JD_MERCHANT');
        //        $param["device"]=$_POST["device"];
        $param["tradeNum"] = "test1493894379";
        $param["tradeName"] = '食得鲜-订单支付';
        $param["tradeDesc"] = "订单支付，金额:" . $amount;
        $param["tradeTime"] = date('YmdHis');
        $param["amount"] = $amount;
        $param["currency"] = "CNY";
        $param["note"] = '食得鲜-订单支付';

        $param["callbackUrl"] = "http://w.shidexian.com/index.php#index4";
        $param["notifyUrl"] = "http://" . $_SERVER['HTTP_HOST'] . "/jd_pay_notice.php";
        //        $param["ip"]= $_POST["ip"];
        //        $param["specCardNo"]= $_POST["specCardNo"];
        //        $param["specId"]= $_POST["specId"];
        //        $param["specName"]= $_POST["specName"];
        //        $param["userType"]= $_POST["userType"];
        $param["userId"] = "0";
        //        $param["expireTime"]= $_POST["expireTime"];
        $param["orderType"] = "0";
        //        $param["industryCategoryCode"]= $_POST["industryCategoryCode"];

        $jdpaySubmit = new JdpaySubmit();

        $html_text = $jdpaySubmit->buildAppRequestParaToString($param);
        //echo $html_text;
        dump($html_text);
    }

    public function test_pay(){
        $param = array();
        $amount = "1";
        $param["version"] = C('JD_VERSION');
        $param["merchant"] = C('JD_MERCHANT');
        //        $param["device"]=$_POST["device"];
        $param["tradeNum"] = "test1493894379";
        $param["tradeName"] = '食得鲜-订单支付';
        $param["tradeDesc"] = "订单支付，金额:" . $amount;
        $param["tradeTime"] = date('YmdHis');
        $param["amount"] = $amount;
        $param["currency"] = "CNY";
        $param["note"] = '食得鲜-订单支付';

        $param["callbackUrl"] = "http://w.shidexian.com/index.php#index4";
        $param["notifyUrl"] = "http://" . $_SERVER['HTTP_HOST'] . "/jd_pay_notice.php";
        //        $param["ip"]= $_POST["ip"];
        //        $param["specCardNo"]= $_POST["specCardNo"];
        //        $param["specId"]= $_POST["specId"];
        //        $param["specName"]= $_POST["specName"];
        //        $param["userType"]= $_POST["userType"];
        $param["userId"] = "0";
        //        $param["expireTime"]= $_POST["expireTime"];
        $param["orderType"] = "0";
        //        $param["industryCategoryCode"]= $_POST["industryCategoryCode"];

        $jdpaySubmit = new JdpaySubmit();

        $html_text = $jdpaySubmit->buildRequestForm($param, 'post', '确认');
        echo $html_text;
        //dump($html_text);

    }
}